package com.kly.sc.api.application.controller.im;

import com.fqgj.common.api.Response;
import com.kly.sc.api.application.controller.im.request.OpenChatReq;
import com.kly.sc.api.application.controller.im.response.ChatterResponse;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.user.ScUserConversationService;
import com.kly.sc.api.application.strategy.RuleTree;
import com.kly.user.dto.UserConversationDto;
import com.kly.user.dto.UserConversationRecordDto;
import com.kly.user.dto.chatter.request.ConversationReq;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.ConversationType;
import com.kly.user.service.UserMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/chat")
public class ChattingController {

    @Autowired
    ScUserConversationService scUserService;

    @Resource
    UserMsgService userMsgService;

    @RequestMapping("/openChat")
    public Response openChatter(@RequestBody OpenChatReq req) {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        String toUserCode = req.getUserCodeFriend();
        ChatterResponse response = new ChatterResponse();
        UserConversationDto userConversation =
                scUserService.getUserConversation(userCode, toUserCode);//查询会话记录
        Map<Integer, List<UserConversationRecordDto>> userRecordListMap =
                scUserService.getUserRecordListMap(userCode, toUserCode, null);//查询权益使用次数

        int firstSessionNumber = Optional.ofNullable(userRecordListMap.get(ConversationType.FIRST_CONVERSATION.getCode()))
                .map(List::size)
                .orElse(0);//获取破冰会话使用数量
        int validSessionNumber = Optional.ofNullable(userRecordListMap.get(ConversationType.EFFECTIVE_CONVERSATIONS.getCode()))
                .map(List::size)
                .orElse(0);//获取有效会话使用数量
        int deepSessionNumber = Optional.ofNullable(userRecordListMap.get(ConversationType.DEEP_CONVERSATIONS.getCode()))
                .map(List::size)
                .orElse(0);//获取深度会话使用数量
        int conversationsNumber =
                Optional.ofNullable(userRecordListMap.get(ConversationType.CONVERSATIONS_NUMBER.getCode()))
                        .filter(list -> !list.isEmpty())
                        .map(list -> list.get(0))
                        .map(UserConversationRecordDto::getConversationsNumber)
                        .orElse(0); //获取此会话中消息总数

        boolean existsFirstSession = Optional.ofNullable(userRecordListMap.get(ConversationType.FIRST_CONVERSATION.getCode()))
                .orElse(Collections.emptyList())
                .stream()
                .anyMatch(record -> toUserCode.equals(record.getToUserCode()));//是否存在破冰会话

        boolean existsValidSession = Optional.ofNullable(userRecordListMap.get(ConversationType.EFFECTIVE_CONVERSATIONS.getCode()))
                .orElse(Collections.emptyList())
                .stream()
                .anyMatch(record -> toUserCode.equals(record.getToUserCode()));//是否存在有效会话

        boolean existsDeepSession = Optional.ofNullable(userRecordListMap.get(ConversationType.DEEP_CONVERSATIONS.getCode()))
                .orElse(Collections.emptyList())
                .stream()
                .anyMatch(record -> toUserCode.equals(record.getToUserCode()));//是否存在深度会话


        if (userConversation.getUserLeaveTime().before(userConversation.getEnterTime())
                || userConversation.getUserLeaveTime().equals(userConversation.getEnterTime())) {

            int msgNumber = userMsgService.selectByCreateDate(userConversation);//查询消息数量

        }
        return null;
    }

    @RequestMapping("/openChat2")
    public Response openChatter2(@RequestBody OpenChatReq req) {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        String toUserCode = req.getUserCodeFriend();

        UserConversationDto userConversation =
                scUserService.getUserConversation(userCode, toUserCode); //查询会话记录

        Map<Integer, List<UserConversationRecordDto>> userRecordListMap =
                scUserService.getUserRecordListMap(userCode, toUserCode, null); //查询权益使用次数

        int conversationsNumber =
                Optional.ofNullable(userRecordListMap.get(ConversationType.CONVERSATIONS_NUMBER.getCode()))
                        .filter(list -> !list.isEmpty())
                        .map(list -> list.get(0))
                        .map(UserConversationRecordDto::getConversationsNumber)
                        .orElse(0); //获取此会话中消息总数

        RuleTree ruleTree = new RuleTree(userRecordListMap, userConversation, toUserCode);
        int allowableMessages = ruleTree.evaluate(userRecordListMap, conversationsNumber);

        ChatterResponse chatterResponse = new ChatterResponse();
        chatterResponse.setMessagesNumber(allowableMessages);
        chatterResponse.setMsgSize(0);
        chatterResponse.setTurnOns(true);

        return Response.ok(chatterResponse);
    }

//    public void processConversation(OpenChatReq req, int conversationsNumber) {
//        int msgNumber = req.getSendMessagesNumber() + conversationsNumber;
//
//        List<UserConversationRecordDto> addConversationRecordList = new ArrayList<>();
//
//        addConversationIfNecessary(msgNumber, ConversationType.FIRST_CONVERSATION, firstSessionNumber, userFirstChat, existsFirstSession, addConversationRecordList);
//        addConversationIfNecessary(msgNumber, ConversationType.EFFECTIVE_CONVERSATIONS, validSessionNumber, UserBehavior.EFFECTIVE_CONVERSATIONS.getLimit(), existsValidSession, addConversationRecordList);
//        addConversationIfNecessary(msgNumber, ConversationType.DEEP_CONVERSATIONS, deepSessionNumber, UserBehavior.DEEP_CONVERSATIONS.getLimit(), existsDeepSession, addConversationRecordList);
//
//        // 添加会话消息数量
//        UserConversationRecordDto conversationRecord = createUserConversationRecord(req, ConversationType.CONVERSATIONS_NUMBER, msgNumber);
//        addConversationRecordList.add(conversationRecord);
//
//        userConversationService.addUserConversationRecordList(addConversationRecordList);
//    }
//
//    private void addConversationIfNecessary(int msgNumber, ConversationType conversationType, int currentSessionNumber, int limit, boolean existsSession, List<UserConversationRecordDto> addConversationRecordList) {
//        if (msgNumber > conversationType.getSize() && currentSessionNumber < limit && !existsSession) {
//            UserConversationRecordDto conversationRecord = createUserConversationRecord(req, conversationType);
//            addConversationRecordList.add(conversationRecord);
//        }
//    }
//
//    private UserConversationRecordDto createUserConversationRecord(OpenChatReq req, ConversationType conversationType, Integer... msgNumber) {
//        UserConversationRecordDto.Builder builder = UserConversationRecordDto.builder()
//                .userCode(userCode)
//                .toUserCode(req.getUserCodeFriend())
//                .conversationsAttributes(GENERAL_USER)
//                .conversationsType(conversationType.getCode());
//
//        if (msgNumber.length > 0) {
//            builder.conversationsNumber(msgNumber[0]);
//        }
//
//        return builder.build();
//    }

}
